package com.lanmaoly.cunzheng;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道，jdk管道为同一进程下不同线程实现通信
 */
public class PipedTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        Thread thread = new Thread(() -> {
            try {
                out.write("Hello World pipe".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread1 = new Thread(() -> {
            try {
                int offset = 0;
                int numRead = 0;
                byte[] bytes = new byte[20];
                while (offset < bytes.length && (numRead = in.read(bytes, offset, 10)) >= 0) {
                    System.out.println(offset);
                    offset += numRead;
                }
                System.out.println(new String(bytes));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
        thread1.start();

        thread.join();
        thread1.join();
        System.out.println("结束");
    }
}
